#include "speed_statistics.h"
#include "base/logging.h"

namespace dl {

SpeedStatistics::SpeedStatistics() 
   : timer_(true, true) {
  start_tick_  = base::TimeTicks::Now();
  total_bytes_ = 0;
}

SpeedStatistics::~SpeedStatistics() {

}

void SpeedStatistics::Start(base::Closure notify) {
  DCHECK(CalledOnValidThread());
  start_tick_  = base::TimeTicks::Now();
  total_bytes_ = 0;
  timer_.Start(FROM_HERE, base::TimeDelta::FromMilliseconds(1000), notify);
}

void SpeedStatistics::Stop() {
  timer_.Stop();
}

void SpeedStatistics::Record(int64 bytes) {
  DCHECK(CalledOnValidThread());
  total_bytes_ += bytes;
}

int64 SpeedStatistics::CurrentSpeed() const {
  DCHECK(CalledOnValidThread());
  base::TimeDelta diff = base::TimeTicks::Now() - start_tick_;
  int64 diff_ms = diff.InMilliseconds();
  return diff_ms == 0 ? 0 : total_bytes_ * 1000 / diff_ms;
}

}